/*
 * Categories View is used for displaying the lists of categories 
 * and subcategories when user has pressed 'Categories' button in 
 * the main view, Places View
 */


qype.views.CategoriesView = Class.create(View, {
    initialize: function($super, id) {
        $super(id);
        this.activeCategory = undefined;
        this.activeCategoryName = undefined;
        this.data.categories = undefined;

        // Create new snippet and bind to a DOM node via id
        var header = new Snippet("categoriesHeader");

        // Add default template
        // header.onDefault.template.push(qype.str.categories_header_main);
        header.onDefault.template.push({
            fn: function() {return (this.activeCategoryName) ?
                                        qype.str.categories_header_sub + " (" + this.activeCategoryName + ")" :
                                        qype.str.categories_header_main},
            base: this
        });

        // Create new snippet and bind to a DOM node via id
        var content = new Snippet("categoriesContent");

        // Add default template
        content.onDefault.template.push("<div class='progress'></div>");
        content.onData.template.push({
            fn: this.constructCategoriesHtml,
            base: this
        });
        content.onData.doUse = function() {return content.data.categories !== undefined;};

        // And finally register the Snippets to this view
        this.registerSnippets({
            header: header,
            content: content
        });

        this.registerSubscribes([
            {
                eventName: "categoryClicked",
                callback: this.onItemClick,
                context: this
            }
        ]);
    },

    templates: {
        showAll: new Template(
            '<div class="item all" onclick="EventManager.publish({name:\'#{eventName}\', id:\'#{id}\', categoryName:\'#{categoryName}\', isLeaf:true})">' +
			'  <div class="name">#{title}</div>' +
			'  <div class="button next"></div>' +
			'</div>'
        ),
        category: new Template(
            '<div class="item" onclick="EventManager.publish({name:\'#{eventName}\', id:\'#{id}\', categoryName:\'#{title}\', isLeaf:#{isLeaf}})">' +
			'  <div class="name">#{title}</div>' +
			'  <div class="button next"></div>' +
			'</div>'
        )
    },

    build: function($super, params) {
        $super(params);

        if(params && params.categoryId) {
            if(this.activeCategory == params.categoryId && this.data.subcategories) {
                this.setCategoriesContent(this.data.subcategories);
                if(params.categoryName) {
                    this.activeCategoryName = params.categoryName;
                }
            }
            else {
                // Set content to 'loading' state
                this.snippets.content.data.categories = undefined;
                
				util.depressurizeAll("item");
                this.snippets.header.rewrite();
                this.snippets.content.rewrite();
                
                this.getSubCategories(params.categoryId, params.categoryName);
            }
        }
        else {
            this.activeCategory = undefined;
            this.activeCategoryName = undefined;
            if(this.data.mainCategories) {
                this.setCategoriesContent(this.data.mainCategories);
            }
            else {
                this.getCategories();
            }
        }
    },

    setCategoriesContent: function(categories) {
        // The content snippet has only one set of categories 
        this.snippets.content.data.categories = categories;
    },

    onItemClick: function(evt) {
       util.log("{CategoriesView.onItemClick} start");

        if(evt.isLeaf) {
            this.engine.activateView("placesView", {categoryId: evt.id, categoryName: evt.categoryName});
        }
        else {
            this.engine.activateView(this.id, {categoryId: evt.id, categoryName: evt.categoryName});
        }
   },

    constructCategoriesHtml: function() {
        var cats = undefined;
        if(cats = this.snippets.content.data.categories) {
            cats = cats.results;
            var arr = [];

            // Add "Show all" item on the top if in a subcategory
            if(this.activeCategory) {
                arr.push(this.templates.showAll.evaluate({
                    id: this.activeCategory,
                    title: qype.str.categories_show_all,
                    categoryName: this.activeCategoryName,
                    eventName: "categoryClicked"
                }));
            }

            var t = this.templates.category;
            for(var i = 0; i < cats.length; i++) {
                var cat = cats[i].category;
                arr.push(t.evaluate({
                    id: cat.id.substring(cat.id.lastIndexOf("/") + 1),
                    title: cat.title.value,
                    eventName: "categoryClicked",
                    isLeaf: cat.links.length < 3
                }));
            }

            return arr.join("");
        }

        return "";
    },

    getCategories: function() {
        qype.API.get("place_categories", {
            "onSuccess": this.onGetCategories.bind(this), 
            "onFailure": this.onFailure
        });
    },

    onGetCategories: function(response) {
        util.log("{CategoriesView.onGetCategories} start");
        this.data.mainCategories = response.responseJSON;
        this.setCategoriesContent(this.data.mainCategories);

        util.depressurizeAll("item");
        this.snippets.header.rewrite();
        this.snippets.content.rewrite();
		util.pressurizeAll("item");
    },

    onFailure: function(response) {
        util.log("{CategoriesView.onFailure}: start, response = ");
        util.log(response);
    },

    /**
     * Deliver also the categoryName along with the function call since it can't
     * be acquired easily when getting the actual subcategories result.
     *
     * Both categoryId and categoryName are set only when the API call is successful.
     */
    getSubCategories: function(categoryId, categoryName) {
        qype.API.get("place_categories", {
            "onSuccess": this.onGetSubCategories.bind(this, categoryId, categoryName),
            "onFailure": this.onFailure
        }, categoryId + "/children");
    },

    onGetSubCategories: function(categoryId, categoryName, response) {
        util.log("{CategoriesView.onGetSubCategories} start");
        this.activeCategory = categoryId;
        this.activeCategoryName = categoryName;

        this.data.subcategories = response.responseJSON;
        this.setCategoriesContent(this.data.subcategories);

        util.depressurizeAll("item");
        this.snippets.header.rewrite();
        this.snippets.content.rewrite();
		util.pressurizeAll("item");
    }
});